home *** CD-ROM | disk | FTP | other *** search
- Path: news.primenet.com!not-for-mail
- From: gbe@primenet.com (Gary Edstrom)
- Newsgroups: comp.lang.c++
- Subject: Re: What is referencing good for?
- Date: 25 Feb 1996 16:47:00 -0700
- Organization: Sequoia Software
- Sender: root@primenet.com
- Message-ID: <3130e9f1.149228054@news.primenet.com>
- References: <4goojd$a9g@wintermute.ecs.fullerton.edu> <4goutn$31u@news.bridge.net> <3130c026.8571250@news2.cts.com>
- X-Posted-By: ip097.lax.primenet.com
- X-Newsreader: Forte Agent .99d/32.182
-
- lboard@cts.com (Larry Board) wrote:
-
- >On 25 Feb 1996 06:17:27 GMT, David Byrden <100101.2547@compuserve.com>
- >wrote:
- >
- >> References are necessary to allow operator overloading.
- >>
- >>class array {
- >>private:
- >> int * dataBlock ;
- >>public :
- >> int& operator[] ( int index )
- >> {
- >> return dataBlock [ index ] ;
- >> }
- >> // constructor etc etc
- >>} ;
- >>
- >> array ar ;
- >> ar[4] = 0 ; // can't be done with pointers
- >
- >Good example, but.... the next question begs to be answered. Why
- >would anybody want to do this? It essentially gives public access to
- >datablock, which is a private variable.
-
- There are many reasons for doing this. For one, I have created an array class
- that does bounds checking at run time. In addition to a pointer to the array,
- I also store the size of the array within the class. I do not need to
- explicity check the index into the array before fetching or storing a value. I
- have the program throw an exception if the index is out of bounds. My array
- class would look as follows:
-
- class array {
- private:
- int size;
- int * dataBlock;
- public:
- int operator [] (int offset) const
- {
- if (offset >= size) throw exception;
- return dataBlock[offset];
- }
- int & operator [] (int offset)
- {
- if (offset >= size) throw exception;
- return dataBlock[offset];
- }
- };
-
- Of course, there are other members that you need to add for a complete
- implementation of the array class. The first version of "operator []" is
- called when the array appears on the right side of an assignment statement.
- The second version is called when the array appears on the left side.
-
- Gary Edstrom
-
- --
- Gary Edstrom <gbe@primenet.com> | Sequoia Software
- PO Box 9573 | Programming & Technical Services
- Glendale CA 91226-0573 | PGP Key ID: 0x1A0D44BD
- PGP Fingerprint: 72 AA 4F 73 05 53 89 C6 8A EE F4 EE D1 C0 13 8D
-